package com.example.java250729_springboot.controller;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

@RequestMapping("/request2")
@RestController
public class RequestController2 {
    /**
     * 读取cookie
     */
    @RequestMapping("/getCookie")
    public String getCookie(HttpServletRequest request){
        //Integer age = Integer.parseInt(request.getParameter("age"));
        Cookie[] cookies = request.getCookies();
        if (cookies != null){
            for (Cookie cookie:cookies) {
                System.out.println(cookie.getName() + ":" + cookie.getValue());
            }
        }
        return "获取Cookie成功";
    }

    @RequestMapping("/getCookie2")
    public String getCookie2(@CookieValue("class") String className){
        return "获取cookie成功，classname：" + className;
    }
    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request){
        HttpSession session = request.getSession();
        //设置用户信息
        session.setAttribute("name","zhangsan");
        session.setAttribute("age",15);
        return "设置session成功";
    }

    @RequestMapping("getSession")
    public String getSession(HttpServletRequest request){
        //从cookie中获取sessionId，并根据sessionID获取httpSession对象
        //没有session时，就会创建一个session
        HttpSession session = request.getSession();
        //获取用户信息
        String name = (String) session.getAttribute("name");
        Integer age = (Integer) session.getAttribute("age");
        return "从session中获取数据，name：" + name + ",age" + age;
    }
    @RequestMapping("/getSession2")
    public String getSession(HttpSession session){
        String name = (String) session.getAttribute("name");
        Integer age = (Integer) session.getAttribute("age");
        return "从session中获取数据，name：" + name + ",age" + age;
    }
    @RequestMapping("/getSession3")
    public String getSession3(@SessionAttribute("name") String name){

        return "从session中获取数据，name：" + name;
    }

    @RequestMapping("/getHeader")
    public String getHeader(HttpServletRequest request){
        String userAgent =  request.getHeader("User-Agent");
        return "从header中获取数据，userAgent：" + userAgent;
    }

    @RequestMapping("/getHeader2")
    public String getHeader2(@RequestHeader("User-Agent") String userAgent){
        return "从header中获取数据，userAgent：" + userAgent;
    }

}
























